﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Revis.VClinicNet.UI.External.Client.View;
using Revis.VClinicNet.UI.External.Client.Service;
using System.Collections.ObjectModel;

namespace Revis.VClinicNet.UI.External.Client.ViewModel
{
    public class CardViewModel : WorkspaceControlViewModelBase<Card>
    {
        public CardViewModel()
        {
            _entriesList = new ReadOnlyCollection<EntryDto>(new List<EntryDto>());
        }

        public override void Run()
        {
            Request();
        }

        public void Request()
        {
            ChangeState("Pobieranie kartoteki", RequestState.Requesting);
            _patientService.BeginCard(new AsyncCallback(RequestEnded), null);
        }

        public void RequestEnded(IAsyncResult result)
        {
            try {
                EntryDto[] entries = _patientService.EndCard(result)
                    .OrderBy(v => v.Date)
                    .ToArray();
                EntriesList = new ReadOnlyCollection<EntryDto>(entries);
                ChangeState("Kartoteka pacjenta została pobrana", RequestState.Success);
            } catch (Exception) {
                ChangeState("Wystąpił poważny błąd podczas pobierania kartoteki", RequestState.Faulted);
            }
        }

        private ReadOnlyCollection<EntryDto> _entriesList;
        public ReadOnlyCollection<EntryDto> EntriesList
        {
            get { return _entriesList; }
            set
            {
                _entriesList = value;
                RaisePropertyChanged("EntriesList");
            }
        }
    }
}
